from sanic.views import HTTPMethodView
from sanic.response import text,json
import time
from processing.other_func import ProToken,Sercret_all,Serialization,Random_id,date_format
import json as jn
import re
from processing.Sql_DataFrom import ProJosn
import requests
from qcloud_cos import CosConfig
from qcloud_cos import CosS3Client
import os
import pickle
from processing.comm import sqlPaging,sqlOrder,set_status,timestamp_to_standard
import requests
from qiniu import Auth, put_data



https = 'https://xiangyou-1313406647.cos.ap-nanjing.myqcloud.com/'

# access_key = 'E6V25lrPSq7LPacKPd7fKhihIQ2bco8K5x2z4Hgp'
#
# secret_key = '0aQ4rneBSJDFDBlgdbHwb62pQH8YQDFdfNFeWnL3'

# 空间名
bucket_name = 'baibaotuju'


def save_binary_image(filename, image_data):
    with open(filename, 'wb') as file:
        # pickle.dump(image_data, file)
        file.write(image_data)


class upload(HTTPMethodView):
    async def post(self, request):
        # 登录用户的id
        user_id = request.app.ctx.user_id
        db = request.app.ctx.db
        secret_id = 'AKIDITP7cw20lOmwttoWCgw0qwrfGm6FCxWx'  # SecretId
        secret_key = 'JQQNHNRSJx8a7XloiPuHZhdTDsLrGWaR'  # SecretKey
        region = 'ap-nanjing'  # COS区域
        bucket = 'xiangyou-1313406647'  # 存储桶名称
        config = CosConfig(Region=region, SecretId=secret_id, SecretKey=secret_key)
        client = CosS3Client(config)
        path = os.path.abspath(__file__)
        path = os.path.dirname(path).replace('views', 'static/')
        file_manage_id = request.form['file_manage_id'][0]

        for i in list(request.files['file']):
            #
            save_binary_image(path + i[2], i[1])

            file_path_cos = f'test/{int(time.time())}_{i[2]}'.replace(',', '')  # {i[2]}
            loadPath = path + i[2]

            with open(loadPath, 'rb') as fp:
                response = client.put_object(
                    Bucket=bucket,
                    Key=file_path_cos,  # cos地址
                    Body=fp,
                    ContentType='image/jpeg'  # 根据上传的文件类型修改
                )
            if response['ETag']:
                os.remove(path + i[2])
                sql = """
                       insert into file_manage(merchant_id,url,suffix,type,file_manage_type,other,ctime) VALUES (%s,%s,%s,%s,%s,%s,now())
                """
                db.insert(sql,
                          (user_id, file_path_cos, file_path_cos.split('.')[-1], '', file_manage_id, str(response)))

        data = {
            'code': 200,
            'message': '上传成功!'
        }

        return json(data)


class filemanage_group_add(HTTPMethodView):
    async def post(self, request):
        # 登录用户的id
        user_id = request.app.ctx.user_id
        db = request.app.ctx.db

        html_data = request.json

        sql = """
                   insert into filemanage_group(merchant_id,name,type,other,ctime) VALUES (%s,%s,%s,%s,now())
                """
        db.insert(sql, (user_id, html_data['name'], html_data['type'], html_data['other']))

        data = {
            'code': 200,
            'message': '创建成功!'
        }

        return json(data)

class filemanage_group_list(HTTPMethodView):
    async def post(self, request):
        # 登录用户的id
        user_id = request.app.ctx.user_id
        db = request.app.ctx.db

        html_data = request.json

        sql = """
                   select id,name,type,ctime,other from filemanage_group where merchant_id=%s
                """

        data = db.find_all(sql, (user_id))
        if data:
            data = ProJosn(data, sql)
        else:
            data = []

        data = {
            'code': 200,
            'data': {
                'list':data
            },
            'message': '请求成功!'
        }

        return json(data)

class filemanage_group_delete(HTTPMethodView):
    async def post(self, request):
        # 登录用户的id
        user_id = request.app.ctx.user_id
        db = request.app.ctx.db

        html_data = request.json

        sql = """
                    delete from filemanage_group where id=%s
                """

        db.delete(sql, (html_data['id']))

        sql1 = "select * from filemanage_group where id=%s"
        if db.find_one(sql1, int(html_data['id'])):
            data = {
                'code': 400,
                'message': '删除失败!'
            }
        else:
            data = {
                'code': 200,
                'message': '删除成功!'
            }

        return json(data)

class filemanage_group_update(HTTPMethodView):
    async def post(self, request):
        # 登录用户的id
        user_id = request.app.ctx.user_id
        db = request.app.ctx.db

        html_data = request.json

        sql = """
                update filemanage_group set name=%s,type=%s,other=%s where id=%s
            """

        db.update(sql, (
            html_data['name'],
            html_data['type'],
            html_data['other'],
            html_data['id']
        ))

        data = {
            'code': 200,
            'message': '请求成功!'
        }

        return json(data)

class get_file_manage(HTTPMethodView):
    async def get(self, request):
        # 登录用户的id
        user_id = request.app.ctx.user_id
        db = request.app.ctx.db

        pageNum = int(request.args.get('pageNum',1))
        pageSize = int(request.args.get('pageSize',10))
        file_manage_id = (request.args.get('file_manage_id','0'))

        sql = f" select id,url,suffix from file_manage where merchant_id=%s"

        # 获取总数据
        tol = f""" SELECT COUNT(*) FROM file_manage where merchant_id='{user_id}'"""

        if file_manage_id == '0' or file_manage_id == 0:
            pass
        else:
            sql = f" select id,url,suffix from file_manage where file_manage_type={file_manage_id} and merchant_id=%s"
            tol = f"SELECT COUNT(*) FROM file_manage where file_manage_type={file_manage_id} and merchant_id='{user_id}'"

        sql = sqlOrder(sql,'ctime','desc')
        # 分页pageNum
        sql = sqlPaging(pageNum, pageSize, sql)


        tol_data = db.find_one(tol)
        data = db.find_all(sql, (user_id))
        #
        if data:
            data = ProJosn(data, sql, 'sql')
        else:
            data = []

        data = {
            'code': 200,
            'data': {
                'list':data,
                'total': tol_data[0],
            },
            'message': '请求成功!'
        }

        return json(data)
class ImageDel(HTTPMethodView):
    async def post(self, request):
        # 登录用户的id
        user_id = request.app.ctx.user_id
        db = request.app.ctx.db

        html_data = request.json

        sql = f" delete from file_manage where"

        sum = 0
        for i in html_data['ids'].split(','):
            if sum == 0:
                sql += f" id={int(i)} "
            else:
                sql += f" or id={int(i)} "
            sum += 1

        db.delete(sql)

        data = {
            'code': 200,
            'message': '删除成功!'
        }
        return json(data)





